import React, { useState, useEffect } from 'react';
import { Users, Phone, Calendar, Shield, UserCheck, ShieldEllipsis, Building, Star} from 'lucide-react';

interface DutyPerson {
  name: string;
  phone: string;
  department: string;
  remarks: string;
  photo?: string;
}

// 数据库返回的数据接口
interface DutyData {
  date: string;
  persons: Array<{
    name: string;
    phone: string;
    department: string;
    remarks: string;
  }>;
}

// 配置接口
interface DutyConfig {
  showLeaderSection: boolean;
  useMockData: boolean;
}

// 添加 Electron API 类型声明
declare global {
  interface Window {
    electronAPI?: {
      getAppInfo: () => Promise<{ version: string; name: string }>;
      getDutyData: (date?: string, useMockData?: boolean) => Promise<{ success: boolean; data?: DutyData; error?: string }>;
      getDutyConfig: () => Promise<{ success: boolean; data?: DutyConfig; error?: string }>;
      testDbConnection: () => Promise<{ success: boolean; message?: string; error?: string }>;
      writeLog: (level: string, message: string, meta?: any) => Promise<{ ok: boolean }>;
    };
  }
}

// 默认数据，当数据库连接失败时使用
const defaultDutyLeader: DutyPerson = {
  name: '— — —',
  phone: '— —',
  department: '— — —',
  remarks: ''
};

const defaultDutyPersons: DutyPerson[] = [
];

function DutyInfo() {
  const [dutyData, setDutyData] = useState<DutyData | null>(null);
  const [dutyConfig, setDutyConfig] = useState<DutyConfig>({ showLeaderSection: true, useMockData: false });
  const [showPhoto, setShowPhoto] = useState(true);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [useDefaultData, setUseDefaultData] = useState(false);

  const currentDate = new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '年').replace(/年(\d+)年/, '年$1月') + '日';

  // 获取值班配置
  const fetchDutyConfig = async () => {
    try {
      if (window.electronAPI) {
        const result = await window.electronAPI.getDutyConfig();
        console.log('getDutyConfig result:', result)
        if (result.success && result.data) {
          setDutyConfig(result.data);
          await window.electronAPI.writeLog('info', '值班配置获取成功', result.data);
        } else {
          await window.electronAPI.writeLog('warn', '值班配置获取失败，使用默认配置', { error: result.error });
        }
      }
    } catch (err) {
      console.error('获取值班配置异常:', err);
      await window.electronAPI?.writeLog('error', '获取值班配置异常', { error: String(err) });
    }
  };

  // 获取值班数据
  const fetchDutyData = async () => {
    try {
      console.log('定时获取fetchDutyData ===> ',new Date());
      if (window.electronAPI) {
        const result = await window.electronAPI.getDutyData(undefined, dutyConfig.useMockData);
        
        if (result.success && result.data) {
          setShowPhoto(true)
          setDutyData(result.data);
          setError(null);
          setUseDefaultData(false);
          console.log('值班数据获取成功：',result.data)
          await window.electronAPI.writeLog('info', '值班数据获取成功', {
            totalPersons: result.data.persons.length
          });
        } else {
          console.error('获取值班数据失败:', result.error);
          setError(result.error || '获取数据失败');
          setUseDefaultData(true);
          await window.electronAPI.writeLog('error', '获取值班数据失败', { error: result.error });
        }
      } else {
        console.warn('ElectronAPI不可用，使用默认数据');
        setUseDefaultData(true);
        await window.electronAPI?.writeLog('warn', 'ElectronAPI不可用，使用默认数据');
      }
    } catch (err) {
      console.error('获取值班数据异常:', err);
      setError('获取数据异常');
      setUseDefaultData(true);
      await window.electronAPI?.writeLog('error', '获取值班数据异常', { error: String(err) });
    } finally {
      setLoading(false);
    }
  };

  // 测试数据库连接
  const testDatabaseConnection = async () => {
    try {
      if (window.electronAPI) {
        const result = await window.electronAPI.testDbConnection();
        if (result.success) {
          await window.electronAPI.writeLog('info', '数据库连接测试成功');
          return true;
        } else {
          await window.electronAPI.writeLog('error', '数据库连接测试失败', { error: result.error });
          return false;
        }
      }
      return false;
    } catch (err) {
      console.error('测试数据库连接异常:', err);
      await window.electronAPI?.writeLog('error', '测试数据库连接异常', { error: String(err) });
      return false;
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    const initializeData = async () => {
      setLoading(true);
      
      // 首先获取配置
      const configResult = await fetchDutyConfigWithReturn();
      
      if (configResult && configResult.useMockData) {
        console.log('使用模拟数据模式，直接获取数据');
        // 直接使用返回的配置数据，不依赖状态
        setDutyData({persons: configResult.mockData || []});
        setLoading(false);
        return;
      }
      
      // 等待一个tick确保状态已更新
      setTimeout(async () => {
        console.log('dutyConfig ===> ', dutyConfig);
        
        // 如果使用模拟数据，直接获取数据，不需要测试数据库连接
        if (dutyConfig.useMockData) {
          console.log('使用模拟数据模式，直接获取数据');
          setDutyData({persons: dutyConfig.mockData || []});
          setLoading(false);
          return;
        }
        
        // 测试数据库连接
        const dbConnected = await testDatabaseConnection();
        
        if (dbConnected) {
          await fetchDutyData();
        } else {
          // 数据库连接失败，使用默认数据
          setUseDefaultData(true);
          setLoading(false);
          await window.electronAPI.writeLog('warn', '数据库连接失败，使用默认数据');
        }
      }, 100);
    };

    initializeData();

    // 设置定时器，每10分钟刷新一次数据
    const interval = setInterval(fetchDutyData, 1 * 60 * 1000);

    return () => clearInterval(interval);
  }, []);

  // 获取值班配置并返回结果
  const fetchDutyConfigWithReturn = async () => {
    try {
      if (window.electronAPI) {
        const result = await window.electronAPI.getDutyConfig();
        console.log('getDutyConfig result:', result);
        if (result.success && result.data) {
          setDutyConfig(result.data);
          await window.electronAPI.writeLog('info', '值班配置获取成功', result.data);
          return result.data;
        } else {
          await window.electronAPI.writeLog('warn', '值班配置获取失败，使用默认配置', { error: result.error });
          return null;
        }
      }
    } catch (err) {
      console.error('获取值班配置异常:', err);
      await window.electronAPI?.writeLog('error', '获取值班配置异常', { error: String(err) });
      return null;
    }
    return null;
  };

  // 获取当前显示的数据
  const getCurrentData = () => {
    if (useDefaultData || !dutyData) {
      return {
        leader: defaultDutyLeader,
        allPersons: defaultDutyPersons
      };
    }

    // 获取所有人员
    const allPersons = dutyData.persons.map(person => ({
      name: person.name,
      phone: person.phone,
      department: person.department,
      remarks: person.remarks
    }));

    // 查找部门包含"领导"的人员，如果存在多个领导仅提取第1个人作为领导
    const leaderPerson = allPersons.find(person => person.department && person.department.includes("领导"));
    
    const leader = leaderPerson ? {
      name: leaderPerson.name,
      phone: leaderPerson.phone,
      department: leaderPerson.department,
      remarks: leaderPerson.remarks,
      photo: `./police_photo/${leaderPerson.name}.jpg` // 使用默认图片
    } : defaultDutyLeader;

    // 值班人员中自动排除上面的领导
    const otherPersons = leaderPerson 
      ? allPersons.filter(person => person.name !== leaderPerson.name)
      : allPersons;

    return {
      leader: leader,
      allPersons: otherPersons
    };
  };

  const currentData = getCurrentData();

  return (
      <div className="min-h-screen w-full relative overflow-hidden bg-gradient-to-br from-slate-900 via-blue-900 to-slate-800">
        {/* 高德地图背景 */}
        <div className="absolute inset-0 opacity-20">
          <img src="./map.png" className="w-full h-full object-cover" alt="地图背景" />
        </div>


        {/* 动态背景效果 */}
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          {/* 粒子效果 */}
          <div className="absolute inset-0">
            {Array.from({ length: 40 }).map((_, i) => (
                <div
                    key={i}
                    className="absolute -top-6 w-4 h-4 bg-cyan-400/20 rounded-full particle-float"
                    style={{
                      left: `${Math.random() * 100}%`,
                      animationDelay: `${Math.random() * 10}s`,
                      animationDuration: `${8 + Math.random() * 6}s`
                    }}
                />
            ))}
          </div>
        </div>

        {/* 主要内容区域 */}
        <div className="relative z-10 h-full flex flex-col px-20 py-20">
          {/* 顶部标题区域 */}
          <div className="text-center mb-20">
            <div className="flex items-center justify-center mb-8">
              <div className="h-1 w-32 bg-gradient-to-r from-transparent via-cyan-400 to-transparent glow-line"></div>
              <div className="mx-8 relative">
                <ShieldEllipsis className="text-cyan-400 drop-shadow-2xl" size={100} />
                <div className="absolute inset-0 bg-cyan-400/20 rounded-full blur-xl animate-pulse"></div>
              </div>
              <div className="h-1 w-32 bg-gradient-to-r from-transparent via-cyan-400 to-transparent glow-line"></div>
            </div>
            <h1 className="text-6xl font-bold text-white mb-6 tracking-wider drop-shadow-2xl">
              值班信息表
            </h1>
            <div className="text-4xl text-cyan-300 tracking-widest opacity-90 font-bold">
              {currentDate}
            </div>
          </div>

          {/* 值班领导区域 - 根据配置显示 */}

            <div className="mb-20">
              <div className="glass-card p-10 border border-cyan-500/30 shadow-2xl card-glow">
                <h2 className="text-5xl font-bold text-white p-10 mb-10 text-center flex items-center justify-center">
                  <Users className="mr-6 text-cyan-400" size={60} />
                  值班领导
                </h2>
                <div className="flex items-center justify-between mb-10" >
                  <div className="flex-1">
                    <div className="glass-item p-8 mb-6">
                      <div className="text-4xl text-gray-300 mb-4">姓名</div>
                      <div className="text-5xl font-bold text-white drop-shadow-lg">{currentData.leader.name}</div>
                    </div>
                    <div className="glass-item p-8 mb-6">
                      <div className="text-4xl text-gray-300 mb-4 flex items-center">
                        <Phone className="mr-4" size={32} />
                        电话
                      </div>
                      <div className="text-5xl font-bold text-white drop-shadow-lg">{currentData.leader.phone}</div>
                    </div>
                    <div className="glass-item p-8">
                      <div className="text-4xl text-gray-300 mb-4 flex items-center">
                        <Building className="mr-4" size={32} />
                        部门
                      </div>
                      <div className="text-5xl font-bold text-white drop-shadow-lg">{currentData.leader.department}</div>
                    </div>
                    {currentData.leader.remarks === '临时指挥长' && (
                      <div className="glass-item p-4 mt-4 bg-red-500/20 border border-red-500/50">
                        <div className="text-3xl text-red-300 font-bold flex items-center">
                          <Star className="mr-4" size={28} />
                          临时指挥长
                        </div>
                      </div>
                    )}
                  </div>
                  {dutyConfig.showLeaderSection && showPhoto && (<div className="ml-12">
                    <div className="glass-item p-2 w-80 h-28 flex items-center justify-center">
                      <img
                        src={currentData.leader.photo || './img.png'}
                        alt="值班领导照片"
                        className="w-full h-full object-cover rounded-lg"
                        onError={(e) => {
                           setShowPhoto(false)
                        }}
                      />
                    </div>
                  </div>)}
                </div>
              </div>
            </div>

          {/* 值班人员区域 - 合并民警和辅警 */}
          <div className="mb-20">
            <div className="glass-card p-12 border border-cyan-500/30 shadow-2xl card-glow site-bg2">
              <h2 className="text-5xl font-bold text-white p-10 mb-10 text-center flex items-center justify-center">
                <UserCheck className="mr-6 text-cyan-400" size={70} />
                值班人员
              </h2>
              <div className="space-y-8 mb-10 glass-item">
                <table className="w-full">
                  <thead>
                  <tr className="border-b border-white/10">
                    <th className="p-6 text-center text-4xl text-gray-300">部门</th>
                    <th className="p-6 text-center text-4xl text-gray-300">姓名</th>
                    <th className="p-6 text-center text-4xl text-gray-300">电话</th>
                  </tr>
                  </thead>
                  <tbody>
                  {currentData.allPersons.map((person, index) => (
                      <tr className="border-b border-white/5 hover:bg-white/5 transition-colors">
                        <td className="py-8 text-center text-3xl text-cyan-300 drop-shadow-lg">{person.department}</td>
                        <td className="py-8 text-center text-4xl font-bold text-white drop-shadow-lg">{person.name}
                          {person.remarks === '临时指挥长' ? (
                              <div className="text-2xl text-red-300 font-bold flex items-center justify-center">
                                <Star className="mr-2" size={24} />
                                临时指挥长
                              </div>
                          ) : null}
                        </td>
                        <td className="py-8 text-center text-4xl text-cyan-300 drop-shadow-lg flex items-center">
                          <Phone className="mr-4" size={28} /> {person.phone}
                        </td>
                      </tr>
                  ))}

                  {/* 无信息的提示 */}
                  {currentData.allPersons.length === 0 && (
                      <tr>
                        <td colSpan={5} className="text-center py-6">
                          <div className="text-3xl text-green-400 font-medium">暂无值班人员</div>
                          <div className="text-xl text-gray-400 mt-2">今日未获取到值班人员数据</div>
                        </td>
                      </tr>
                  )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
  );
}

export default DutyInfo;